﻿package com.powerunion.extjs.utils;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import com.powerunion.datacollection.persistence.db.jdbc.operator.QueryOperator;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlParameter;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlType;
import com.powerunion.datacollection.persistence.pagination.PageParameter;
//import org.hibernate.Query;
//import com.newsoft.excelimp.vo.ColumnParaVo;
//import com.newsoft.util.base64.Encrypt;
/**
 * <p>
 * Title: davi
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Company: newsoft
 * </p>
 * 
 * @author davi
 * @version 1.0
 */
public class Convert {
	public String sql = null;
	public HttpServletRequest request = null;
	/**
	 * 将id字符串转换为标准的数据库查询字符串,分割符为token
	 * 
	 * @param id
	 * @param token
	 * @return
	 */
	public String arrayToString(String id, String token) {
		String ret = "";
		String[] array = id.split(",");
		if ((null != array) && (array.length > 0)) {
			for (int i = 0; i < array.length; i++) {
				ret = ret + "'" + array[i] + "'";
				if (i != array.length - 1)
					ret = ret + token;
			}
		}
		return ret;
	}

	public String String(String s) {
		if (s == null || s.equals("") || s.equals("null"))
			return " ";
		return s;
	}

	public Long Long(String s) {
		s = s.trim();
		if (s == null || s.equals("") || s.equals("null")) {
			return new Long(0);
		}
		return new Long(s);
	}

	public Double Double(String s) {
		s = s.trim();
		if (s == null || s.equals("") || s.equals("null"))
			return new Double(0);
		return new Double(s);
	}

	public Integer Integer(String s) {
		s = s.trim();
		if (s.indexOf(".") >= 0)
			s = s.substring(0, s.indexOf("."));
		if (s == null || s.equals("") || s.equals("null"))
			return new Integer(0);
		return new Integer(s);
	}

	public Date Date(String s) {
		Date date = DateTimeUtil.StringToDate(s);
		return date;
	}

	public Date nowDate() {
		return DateTimeUtil.nowDate();
	}
	
	public QueryOperator getParams(QueryOperator query, Object paramsO) {
		if (paramsO != null) {
			String[] params = (String[])paramsO;
			for (int i = 0; i < params.length; i++) {
				query.addParameter(new SqlParameter(SqlType.VARCHAR, params[i]));
			}
		}
		return query;
	}
	
	public PageParameter getPageParams(PageParameter parameter, Object paramsO) {
		if (paramsO != null) {
			String[] params = (String[])paramsO;
			for (int i = 0; i < params.length; i++) {
				parameter.addParameter(new SqlParameter(SqlType.VARCHAR, params[i]));
			}
		}
		return parameter;
	}

//	public Query getParams(Query query, String[][] params) {
//		if (params != null) {
//			String[] pValue = params[0];// 参数值
//			String[] pType = params[1]; // 参数值类型
//			for (int i = 0; i < pValue.length; i++) {
//				if (pType[i].equals("String")) {
//					query.setParameter(i, String(pValue[i]));
//				} else if (pType[i].equals("Long") || pType[i].equals("Integer")) {
//					query.setParameter(i, Long(pValue[i]));
//				} else if (pType[i].equals("Double")) {
//					query.setParameter(i, Double(pValue[i]));
//				} else if (pType[i].equals("Date")) {
//					query.setParameter(i, Date(pValue[i]));
//				}
//			}
//		}
//		return query;
//	}

//	public String encrypt(String value) {
//		return Encrypt.get(value);
//	}

	public String toGbk(String value) {
		// try {
		// if (value != null){
		// value = new String(value.getBytes("GBK"), "ISO8859_1");
		// }
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		return value;
	}

	public String toIso(String input) {
		if (input == null || input.indexOf("null") >= 0)
			return "";
		// try {
		// if (input != null && input.indexOf("null") < 0) {
		// byte bytes[] = input.getBytes("ISO8859_1");
		// input = new String(bytes);
		// }
		// else {
		// input = " ";
		// }
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		return input;
	}

	public String toTree(Collection rs) {
		String str = "";
		if (!rs.isEmpty()) {
			for (Iterator it = rs.iterator(); it.hasNext();) {
				Object obj[] = (Object[]) it.next();
				String leaf = "";
				if ((obj[1] + "").indexOf("END") >= 0) {// 如果存在END字符串，则表示没有子节点
					leaf = ",'leaf': true";
					obj[1] = (obj[1] + "").replaceAll("END", "");
				}
				String col = "'text':'" + obj[0] + "'," + "'id'	:'" + obj[1]
						+ "'," + "'cls' :'folder'" + leaf;
				str += "{" + col + "},";
			}
		}
		else{
			return "";
		}
		str = "[\n" + str + "]";
		str = str.replaceAll(",]", "\n]");
		return str;
	}

	public String toCombobox(Collection rs) {
		String[] colName = { "text", "value" };
		String str = "";
		if (!rs.isEmpty()) {
			for (Iterator it = rs.iterator(); it.hasNext();) {
				String col = "";
				Object obj[] = (Object[]) it.next();
				for (int i = 0; i < obj.length; i++) {
					if(i == 1 && obj[i].toString().indexOf("\\|") < 0){
						obj[i] = obj[i] + "\\|" + obj[0];
					}
					col += "'" + colName[i] + "':'" + toIso(obj[i] + "',");
				}
				str += "{" + col + "},";
				str = str.replaceAll(",}", "}");
			}
		}

		str = "{'rows':[ " + str + "]}";
		str = str.replaceAll(",]}", "]}");
		return str;
	}

	public String toString(Collection rs) {
		// String[] colName = {"value", "text"};
		String str = "";
		if (!rs.isEmpty()) {
			for (Iterator it = rs.iterator(); it.hasNext();) {
				String col = "";
				Object obj[] = (Object[]) it.next();
				for (int i = 0; i < obj.length; i++) {
					// col += colName[i] + ":'" + toIso(obj[i]+"',");
					col += "'" + toIso(obj[i] + "',");
				}
				str += "[" + col + "],";
				str = str.replaceAll(",]", "]");
			}
		}
		str = "[" + str + "]";
		str = str.replaceAll("],]", "]]");
		return str;
	}

	public String[] contvertColumnName(String sql) {
		String colName = sql.substring(sql.indexOf("select") + 6, sql.lastIndexOf("from")).replace("A.", "").replace("B.", "").replace("C.", "").replace("D.", "");
		
		while(colName.indexOf("(") >= 0){
			int rindex =  colName.indexOf(")");
			int lindex = colName.substring(0, rindex).lastIndexOf("(");
			colName = colName.substring(0, lindex) + colName.substring(rindex + 1);
		}
		
		String[] colNameArray = colName.split(",");
		for (int i = 0; i < colNameArray.length; i++) {
			colNameArray[i] = colNameArray[i].indexOf(" as ") >= 0 ? colNameArray[i].split(" as ")[1] : colNameArray[i];
			colNameArray[i] = colNameArray[i].replaceAll(" ", "").replaceAll("\"", "");
			colNameArray[i] = colNameArray[i].trim();
		}
		return colNameArray;
	}

	public String toComboboxMutiValue(Collection rs,String[] colName) {//2001010057
		colName[0] = "text";
		colName[1] = "value";		
		String str = "";
		if (!rs.isEmpty()) {
			for (Iterator it = rs.iterator(); it.hasNext();) {
				String col = "";
				Object obj[] = (Object[]) it.next();
				if(null==obj[1]) continue;
				for (int i = 0; i < obj.length; i++) {
					if(i == 1 && obj[i].toString().indexOf("\\|") < 0){
						obj[i] = obj[i] + "\\|" + obj[0];
					}
					
					col += "'" + colName[i] + "':'" + toIso(obj[i]+"") + "',";
				}
				
				str += "{" + col + "},";
				str = str.replaceAll(",}", "}");
			}
		}
		str = "{'rows':[ " + str + "]}";
		str = str.replaceAll(",]}", "]}");
		

		return str;
	}	
	
	public String toXml(Collection rs, String sql, String totalCount,
			int pageStart, int pageSize) {
		return toXml(rs, sql, totalCount, pageStart, pageSize, null);
	}

	public String toXml(Collection rs, String sql,
			int pageStart, int pageSize) {
		return toXml(rs, sql, rs.size() + "", pageStart, pageSize, null);
	}
	
	public String toXml(Collection rs, String sql, String totalCount) {
		return toXml(rs, sql, totalCount, 0, 0, null);
	}
	
	public String toXml(Collection rs, String sql) {
		return toXml(rs, sql, rs.size() + "", 0, 0, null);
	}
	
	public String toXml(Collection rs, String sql, String totalCount,
			int pageStart, int pageSize, String Omissions) {
		String str = "";
		String[] colNameArray = this.contvertColumnName(sql);
		int _colNo = 1;
		int _pageNo = pageSize == 0 ? 0 : pageStart / pageSize;
		if (!rs.isEmpty()) {
			for (Iterator it = rs.iterator(); it.hasNext();) {
				String col = "";
				Object obj[] = (Object[]) it.next();
				for (int i = 0; i < colNameArray.length; i++) {
					if (Omissions == null || (i + "").indexOf(Omissions) < 0) {
						String tag = colNameArray[i];
						if (i == 0) {
							int no = _pageNo * pageSize + (_colNo++);
							col += "<" + tag + ">{'id':'" + obj[i]
									+ "', 'no':'" + no + "', 'pageNo':"
									+ (_pageNo + 1) + "}</" + tag + ">\n";
						} else {
							col += "<" + tag + ">" + toIso(obj[i] + "").trim() + "</"
									+ tag + ">\n";
						}
					}
				}
				str += "<rows>\n" + col + "</rows>\n";
				
			}
		}
		str = "<root>\n<TotalCount>" + totalCount + "</TotalCount>" + str
				+ "\n</root>";
		return str;
	}

	public String toJson(Collection rs, String sql, String totalCount,
			int pageStart, int pageSize) {
		return toJson(rs, sql, totalCount, pageStart, pageSize, null);
	}

	public String toJson(Collection rs, String sql, String totalCount,
			int pageStart, int pageSize, String Omissions) {
		String str = "";
		String[] colNameArray = this.contvertColumnName(sql);
		int _colNo = 1;
		int _pageNo = pageStart / pageSize;
		if (!rs.isEmpty()) {
			for (Iterator it = rs.iterator(); it.hasNext();) {
				String col = "";
				Object obj[] = (Object[]) it.next();
				for (int i = 0; i < obj.length; i++) {
					if (Omissions == null || (i + "").indexOf(Omissions) < 0) {
						String tag = colNameArray[i];
						if (i == 0) {
							int no = _pageNo * pageSize + (_colNo++);
							col += "'" + tag + "':{'id':'" + obj[i]
									+ "', 'no':'" + no + "', 'pageNo':"
									+ (_pageNo + 1) + "},";
						} else if (i == obj.length - 1) {
							col += "'" + tag + "':'" + toIso(obj[i] + "") + "'";
						} else {
							col += "'" + tag + "':'" + toIso(obj[i] + "") + "',";
						}
					}
				}
				str += "{" + col + "},";

			}
		}
		str = "({'TotalCount':'" + totalCount + "','rows':["
				+ (str + "]})").replaceAll("},]", "}]");
		return str;
	}

	public List toJson(Collection rs, String sql) {
		List list = new ArrayList();
		String[] colNameArray = this.contvertColumnName(sql);
		if (!rs.isEmpty()) {
			for (Iterator it = rs.iterator(); it.hasNext();) {
				String col = "";
				Object obj[] = (Object[]) it.next();
				for (int i = 0; i < obj.length; i++) {
					String tag = colNameArray[i];
					if (i == obj.length - 1) {
						col += "'" + tag + "':'" + obj[i] + "'";
					} else {
						col += "'" + tag + "':'" + obj[i] + "',";
					}
				}
				String str = "{" + col + "}";
				list.add(str);
			}
		}
		return list;
	}
	
	public String toJsonString(Collection rs, String sql) {
		List list = this.toJson(rs, sql);
		return list.toString();
	}
	// public List getColumn() {
	// Configuration conf = new Configuration();
	// conf.configure(HibernateSessionFactory.CONFIG_FILE_LOCATION);
	// Iterator iter = conf.getTableMappings();
	//	
	// while ( iter.hasNext() ) {
	// Table table = (Table) iter.next();
	// System.out.println(table.getName());
	//	
	// Iterator ics = table.getColumnIterator();
	// while (ics.hasNext()){
	// Column col = (Column) ics.next();
	// System.out.println(col.getCanonicalName());
	// }
	//			
	// }
	// return null;
	// }

	public String isEmpty(String input) {
		if (input == null || input.indexOf("null") >= 0)
			return "";
		else
			return input;
	}

	/**
	 * 从request中获得参数值
	 * 
	 * @return string
	 */
	public String getRequest(String parameter) {
		if (this.request == null)
			return "";
		return this.isEmpty(this.request.getParameter(parameter));
	}

	/**
	 * @param request
	 *  要设置的 request
	 */
	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	/**
	 * 执行某对象的方法
	 * @param owner
	 * @param methodName
	 * @param args
	 * @return Object
	 */
	public Object invokeMethod(Object owner, String methodName, Object[] args){
	    Class ownerClass = owner.getClass();
	    Class[] argsClass = new Class[args.length];
	    for (int i = 0, j = args.length; i < j; i++) {
	        argsClass[i] = args[i].getClass();
	        if(("org.apache.catalina.connector.RequestFacade").equals(argsClass[i].getName())){
	        	argsClass[i] = javax.servlet.http.HttpServletRequest.class;
	        }
	    }
		try {
			Method method = ownerClass.getMethod(methodName, argsClass);
			return method.invoke(owner, args);
		} catch (SecurityException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}
	    return null;
	}
	public Object invokeMethod(Object owner, String methodName){
		return this.invokeMethod(owner, methodName, new Object[0]);
	}
	
	/**
	 * 得到某个对象的属性
	 * @param owner
	 * @param fieldName
	 * @return Object
	 */
//	public Object getProperty(Object owner, String fieldName){
//	    Class<?> ownerClass = owner.getClass();
//		try {
//			Field field = ownerClass.getField(fieldName);
//		    Object property = field.get(owner);
//		    return property;
//		} catch (SecurityException e) {
//			// TODO 自动生成 catch 块
//			e.printStackTrace();
//		} catch (NoSuchFieldException e) {
//			// TODO 自动生成 catch 块
//			e.printStackTrace();
//		} catch (IllegalArgumentException e) {
//			// TODO 自动生成 catch 块
//			e.printStackTrace();
//		} catch (IllegalAccessException e) {
//			// TODO 自动生成 catch 块
//			e.printStackTrace();
//		}
//		return null;
//	}
	/**
	 * 打印某对象所有get方法的值
	 * @param owner
	 */
	public void test(Object owner){
		if (owner==null) {
			System.err.println("----------------------- is null-----------------------");
			return;
		}
		Class ownerClass = owner.getClass();

		Method[] methods = ownerClass.getDeclaredMethods();
		int j = 0;
		System.err.println("-----------------------classname:"+ownerClass.getName()+"-----------------------");
		for (int i = 0; i < methods.length; i++) {
			Method m = methods[i];
			String methodName = m.getName();
			if (methodName.startsWith("get")) {
				System.err.println("["+(j++)+"]"+methodName+":"+this.invokeMethod(owner, methodName));
			}
		}
		System.err.println("-----------------------end-----------------------");
	}
	
//	public static void arrayCopy(ColumnParaVo[] src, int i, ColumnParaVo[] dest, int j,
//			int length) {
//		try {
//			for (int k = 0; k < length; k++) {
//				dest[j] = (ColumnParaVo) src[i].clone();
//				i++;
//				j++;
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}
	
//	public Query getParams(Query query, Object params) {
//		if (params != null) {
//			if(params.getClass()==String[].class){
//				return this.getParams(query, (String[])params);
//			}
//			else{
//				return this.getParams(query, (String[][])params);
//			}
//		}
//		return query;
//	}
	
	/**
	 * get mark number  by instr
	 * @param str
	 * @param mark
	 * @return
	 */
	public int getMarkNum(String instr,String mark){
		if(null==instr || instr.trim().equals("")) return 0;
		String str = instr.trim();
		String[] t = str.split("\\"+mark);
		return str.endsWith(mark) ? t.length  : t.length-1;
	}
	
	
	public static void main(String[] args) throws Exception {
		
		String a = "o.b.c.e".replace(".", "").replace("C.", "");
		System.out.println("ddd"+a);
//		Convert c = new Convert();
////		String b = "a,b,c,d,e,f";
////		System.out.println(c.arrayToString(b, ","));
////		AClinicdetailTemp po = new AClinicdetailTemp();
////		po.setIdno("bbbbbbbbb");
////		c.test(po);
//		String[][] params = null;
//		Object obj = Instance.create("YbUnitAcceManage");
//		c.invokeMethod(obj, "setParams", new Object[]{new String[0]}); 	//查询参数
//		c.invokeMethod(obj, "setPageStart", new Object[]{0}); 	//起始行
//		c.invokeMethod(obj, "setPageSize", new Object[]{10}); 	//每页显示条数		
//    	System.out.println(
//    			(String) c.invokeMethod(obj, "list")
//		);		
	}
}
